package com.coolgor.axnut.schedule.mdmis;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.coolgor.axnut.dto.mdmis.PolicyMonitorExecution;
import com.coolgor.axnut.dto.mdmis.TaskTraceExecution;
import com.coolgor.axnut.entity.mdmis.PolicyMonitor;
import com.coolgor.axnut.entity.mdmis.TaskTrace;
import com.coolgor.axnut.entity.mdmis.TaskTraceCondition;
import com.coolgor.axnut.enums.mdmis.PolicyMonitorOperationStateEnum;
import com.coolgor.axnut.service.mdmis.PolicyMonitorTaskService;
import com.coolgor.axnut.service.mdmis.TaskTraceService;

@Component
public class PolicyMonitorTask {

	@Autowired
	TaskTraceService taskTraceService;	
	
	@Autowired
	PolicyMonitorTaskService policyMonitorTaskService;	
	
	/** 每天晚上21:00、22:00、23:00
	 *  检查当天是否存在相同电话的保单
	 *  如果有则新增/修改一条警告记录
	 */ // http://cron.qqe2.com/
//	@Scheduled(cron = "0 0/1 * * * ? ") //测试用 每分钟执行一次
	@Scheduled(cron = "0 0 21,22 * * ? ") 
    public void checkTheSamePhoneOnDay() {
		TaskTraceCondition taskTraceCondition = new TaskTraceCondition();
		taskTraceCondition.setTaskName("检查当天是否存在相同电话的保单");
		taskTraceCondition.setTaskTimeBegin(new Date(System.currentTimeMillis()));
		taskTraceCondition.setTaskTimeEnd(new Date(System.currentTimeMillis()));
		taskTraceCondition.setResult("success");
		TaskTraceExecution taskTraceExecution = taskTraceService.getTaskTraceList(taskTraceCondition, 0, 9999);
		if (taskTraceExecution.getCount() == 0) {
			TaskTrace taskTrace = new TaskTrace();
			taskTrace.setTaskID(1L);
			taskTrace.setTaskName("检查当天是否存在相同电话的保单");
			taskTrace.setTaskTime(new Date(System.currentTimeMillis()));
			PolicyMonitorExecution exe = policyMonitorTaskService.markWarmTheSamePhoneOnDay();
			if (exe.getState()==PolicyMonitorOperationStateEnum.SUCCESS.getState()
				|| exe.getState()==PolicyMonitorOperationStateEnum.EMPTY_LIST.getState()) {
				String operationInfo ;
				//获取今天日期
				Date today = new Date(System.currentTimeMillis());
				//设置日期格式
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				if (exe.getCount()==0) {
					operationInfo = "["+sdf.format(today)+"]\\n" + "未发现相同电话的保单";
				} else {
					operationInfo = "["+sdf.format(today)+"]\\n发现"+exe.getCount()+"件保单相同电话：\\n" ;
					List<PolicyMonitor> list = exe.getList();
					for (PolicyMonitor pm : list) {
						operationInfo += pm.getInsureNo()+"、" ;
					}
				}
				taskTrace.setOperation(operationInfo);
				taskTrace.setResult("success");
			} else {
				taskTrace.setResult("false");
			}
			taskTraceService.addTaskTrace(taskTrace);
		} 
    }
}
